import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_utils/screen.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import '../../../tools_base/debug_log.dart';

class ImageScaleView extends StatefulWidget {
  final String? url;
  final bool isPage;

  const ImageScaleView({
    Key? key,
    this.url,
    this.isPage = false,
  });

  @override
  State<StatefulWidget> createState() {
    return _ZoomImageViewState();
  }
}

class _ZoomImageViewState extends State<ImageScaleView> with SingleTickerProviderStateMixin {
  AnimationController? _controller;
  Animation<Offset>? _animation;
  Offset _offset = Offset.zero;
  double _scale = 1.0;
  Offset? _normalizedOffset;
  double _previousScale = 0;
  final double _kMinFlingVelocity = 600.0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    _controller?.addListener(() {
      setState(() {
        _offset = _animation?.value ?? Offset.zero;
      });
    });
  }

  Offset _clampOffset(Offset offset) {
    Size? size = context.size;
    // widget的屏幕宽度
    final Offset minOffset = Offset(size?.width ?? 0, size?.height ?? 0) * (1.0 - _scale);
    // 限制他的最小尺寸
    return Offset(offset.dx.clamp(minOffset.dx, 0.0), offset.dy.clamp(minOffset.dy, 0.0));
  }

  void _handleOnScaleStart(ScaleStartDetails details) {
    debugLog("_handleOnScaleStart");
    _previousScale = _scale;
    _normalizedOffset = (details.focalPoint - _offset) / _scale;
    // 计算图片放大后的位置
    _controller?.stop();
    setState(() {});
  }

  void _handleOnScaleUpdate(ScaleUpdateDetails details) {
    _scale = (_previousScale * details.scale).clamp(1.0, 3.0);
    // 限制放大倍数 1~3倍
    _offset = _clampOffset(details.focalPoint - (_normalizedOffset ?? Offset.zero) * _scale);
    // 更新当前位置
    setState(() {});
  }

  void _handleOnScaleEnd(ScaleEndDetails details) {
    final double magnitude = details.velocity.pixelsPerSecond.distanceSquared;
    if (magnitude < _kMinFlingVelocity) return;
    final Offset direction = details.velocity.pixelsPerSecond / magnitude;
    // 计算当前的方向
    final double distance = (Offset.zero & (context.size ?? Size.zero)).shortestSide;
    // 计算放大倍速，并相应的放大宽和高，比如原来是600*480的图片，放大后倍数为1.25倍时，宽和高是同时变化的
    _animation = _controller?.drive(Tween<Offset>(begin: _offset, end: _clampOffset(_offset + direction * distance)));
    _controller
      ?..value = 0.0
      ..fling(velocity: magnitude / 1000.0);
    setState(() {});
  }

  _onDoubleTap() {
    if (_scale > 1) {
      _scale = 1;
    } else {
      _scale = (_previousScale * 1.1).clamp(1.0, 3.0);
      _scale = 2.0;
    }
    // 限制放大倍数 1~3倍
    Size size = context.size ?? Size.zero;
    _offset = Offset(-(size.width / 2), -(size.height / 2));

    final double magnitude = _kMinFlingVelocity;
    final Offset direction = const Offset(20, 20) / magnitude;
    // 计算当前的方向
    final double distance = (Offset.zero & (context.size ?? Size.zero)).shortestSide;
    // 计算放大倍速，并相应的放大宽和高，比如原来是600*480的图片，放大后倍数为1.25倍时，宽和高是同时变化的
    _animation = _controller?.drive(Tween<Offset>(begin: _offset, end: _clampOffset(_offset + direction * distance)));
    _controller
      ?..value = 0.0
      ..fling(velocity: magnitude / 1000.0);

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isPage) {
      return Scaffold(
        body: Stack(
          fit: StackFit.expand,
          children: [
            _buildContent(),
            Positioned(
              top: screen.paddingTop,
              left: 16,
              child: InkWell(
                onTap: () => Get.back(),
                child: Image.asset(
                  "back_circle.png".commonImgPath,
                  width: 24,
                ),
              ),
            ),
          ],
        ),
      );
    }
    return _buildContent();
  }

  Widget _buildContent() {
    return GestureDetector(
      onScaleStart: _handleOnScaleStart,
      onScaleUpdate: _handleOnScaleUpdate,
      onScaleEnd: _handleOnScaleEnd,
      onDoubleTap: _onDoubleTap,
      behavior: HitTestBehavior.translucent,
      child: SizedBox.expand(
        child: ClipRect(
          child: Transform(
            transform: Matrix4.identity()
              ..translate(_offset.dx, _offset.dy)
              ..scale(_scale),
            child: NetworkImageLoader(
              imageUrl: widget.url ?? '',
              width: MediaQuery.of(context).size.width,
              fit: BoxFit.fitWidth,
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();
  }
}
